// Package chaos 包含故障微服务的故障对象，故障对象组合，各种故障对象组合形成的列表，客户端故障的定义
package chaos

import (
	"fmt"
	"goproject/api/v1alpha1"
	"goproject/logger"
	"reflect"
)

func setSelectorFields(value reflect.Value, namespaces []string, labelSelectors map[string]string) (err error) {
	selectorField := value.FieldByName("Selector")

	if selectorField.IsValid() {
		namespacesField := selectorField.FieldByName("Namespaces")
		labelSelectorsField := selectorField.FieldByName("LabelSelectors")

		if namespacesField.IsValid() && namespacesField.CanSet() {
			namespacesField.Set(reflect.ValueOf(namespaces))
		} else {
			return fmt.Errorf("namespacesField is not valid or can not set")
		}

		if labelSelectorsField.IsValid() && labelSelectorsField.CanSet() {
			labelSelectorsField.Set(reflect.ValueOf(labelSelectors))
		} else {
			return fmt.Errorf("labelSelectorsField is not valid or can not set")
		}
	} else {
		return fmt.Errorf("selectorField is not valid or can not set")
	}
	return
}

func SetPodSelectorFields(element v1alpha1.InnerObject, namespaces []string, labelSelectors map[string]string) (err error) {
	log := logger.GetLogger()
	elemType := reflect.TypeOf(element)
	elemValue := reflect.ValueOf(element)

	if elemType.Kind() == reflect.Ptr {
		elemType = elemType.Elem()
		elemValue = elemValue.Elem()
	}

	specField := elemValue.FieldByName("Spec")
	if !specField.IsValid() {
		return fmt.Errorf("specField is not valid or can not set")
	}

	// 检查 Spec 中的字段
	for i := 0; i < specField.NumField(); i++ {
		field := specField.Type().Field(i)
		fieldValue := specField.Field(i)

		if field.Type == reflect.TypeOf(v1alpha1.PodSelector{}) ||
			field.Type == reflect.TypeOf(v1alpha1.ContainerSelector{}) {
			if fieldValue.Kind() == reflect.Struct {
				//fmt.Printf("setSelectorFields: %s\n", field.Name)
				log.Debugf("setSelectorFields: %s\n", field.Name)
				err = setSelectorFields(fieldValue, namespaces, labelSelectors)
				if err != nil {
					err = fmt.Errorf("setSelectorFields: %w", err)
					return
				}
			}
		}
	}
	return
}
